<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\controller\v1\passport;

use app\adminapi\services\passport\PassportService;
use app\adminapi\validate\passport\PassportValidate;
use Exception;
use kitego\base\BaseController;
use kitego\extend\login\admin\AdminLoginBase;
use kitego\extend\login\admin\AdminLoginProvider;
use kitego\extend\login\admin\enum\AdminLoginEnum;
use kitego\utils\captcha\CaptchaUtil;
use kitego\utils\clickcaptcha\ClickCaptchaUtil;
use kitego\utils\SnowflakeUtil;
use think\App;
use think\response\Json;

class PassportController extends BaseController
{
    public array $safeAction = ['all'];

    private PassportService $service;

    public function __construct(App $app, PassportService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 获取验证码
     * @throws Exception
     */
    public function getCaptcha(): Json
    {
        return success([
            'captcha' => 'data:image/png;base64,' . base64_encode(app()->make(CaptchaUtil::class)->create()->getData())
        ]);
    }

    /**
     * 获取点选验证码
     * @throws Exception
     */
    public function getClickCaptcha(): Json
    {
        $id = !empty($this->params['id']) ? $this->params['id'] : SnowflakeUtil::makeSnowflakeId();

        return success(app()->make(ClickCaptchaUtil::class)->create($id));
    }

    /**
     * 登录获取TOKEN
     */
    public function getToken()
    {
        Validate(PassportValidate::class)->scene('getToken')->check($this->params);

        return app()->make(AdminLoginProvider::class, [$this->params['loginWay']])->getStrategy()->login($this->params);
    }

    /**
     * 刷新token
     */
    public function refreshToken()
    {
        Validate(PassportValidate::class)->scene('refreshToken')->check($this->params);

        return app()->make(AdminLoginBase::class)->refreshToken($this->params['refreshToken']);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Validate(PassportValidate::class)->scene('logout')->check($this->params);

        return app()->make(AdminLoginBase::class)->logout($this->params['userId']);
    }
}